﻿using System;
using System.Web;
using NHibernate.Context;

namespace Bussiness.Utilities
{
    public class HibernateCurrentSessionWebModule : IHttpModule
    {
        #region IHttpModule Members

        public void Init(HttpApplication context)
        {
            context.BeginRequest += Application_BeginRequest;
            context.EndRequest += Application_EndRequest;
        }

        public void Dispose()
        {
        }

        #endregion

        private void Application_BeginRequest(object sender, EventArgs e)
        {
            var session = HibernateHelper.OpenSession();
            session.BeginTransaction();
            CurrentSessionContext.Bind(session);
        }

        private void Application_EndRequest(object sender, EventArgs e)
        {
            var session = CurrentSessionContext.Unbind(HibernateHelper.SessionFactory);
            if (session == null) return;
            try
            {
                session.Transaction.Commit();
            }
            catch (System.Exception)
            {
                session.Transaction.Rollback();
            }
            finally
            {
                session.Close();
            }
        }
    }
}